<template>
  <div class="data-management-page">
    <el-card class="page-header">
      <template #header>
        <div class="card-header">
          <span>数据管理</span>
          <el-button type="primary" @click="refreshData" :loading="loading">刷新</el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总批次" :value="getTotalBatches()" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="总记录" :value="getTotalRecords()" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="今日批次" :value="statistics.todayBatches" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="今日记录" :value="statistics.todayRecords" />
        </el-col>
      </el-row>
    </el-card>

    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="批次ID">
          <el-input v-model="filterForm.batchId" placeholder="请输入批次ID" />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="filterForm.category" placeholder="请选择数据类型" clearable>
            <el-option label="银行流水" value="bank" />
            <el-option label="销售订单" value="sales_order" />
            <el-option label="采购订单" value="purchase_order" />
            <el-option label="进项发票" value="incoming_invoice" />
            <el-option label="销项发票" value="outgoing_invoice" />
            <el-option label="发票" value="invoice" />
            <el-option label="未知" value="unknown" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="filterForm.status" placeholder="请选择处理状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="已处理" value="processed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据记录列表</span>
        </div>
      </template>
      <el-table :data="dataItems" style="width: 100%" v-loading="loading">
        <el-table-column prop="itemId" label="数据项ID" width="180" />
        <el-table-column prop="batchId" label="批次ID" width="180" />
        <el-table-column prop="category" label="数据类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.category === 'bank'">银行流水</el-tag>
            <el-tag v-else-if="scope.row.category === 'sales_order'" type="success">销售订单</el-tag>
            <el-tag v-else-if="scope.row.category === 'purchase_order'" type="warning">采购订单</el-tag>
            <el-tag v-else-if="scope.row.category === 'incoming_invoice'" type="info">进项发票</el-tag>
            <el-tag v-else-if="scope.row.category === 'outgoing_invoice'" type="info">销项发票</el-tag>
            <el-tag v-else-if="scope.row.category === 'invoice'" type="info">发票</el-tag>
            <el-tag v-else type="danger">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="请求URL" show-overflow-tooltip />
        <el-table-column prop="method" label="方法" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'pending'">待处理</el-tag>
            <el-tag v-else-if="scope.row.status === 'processed'" type="success">已处理</el-tag>
            <el-tag v-else-if="scope.row.status === 'failed'" type="danger">失败</el-tag>
            <el-tag v-else>{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click="reprocessItem(scope.row)" :loading="scope.row.reprocessing">
              重新处理
            </el-button>
            <el-button size="small" type="danger" @click="deleteItem(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :pager-count="7"
        />
      </div>
    </el-card>

    <!-- 数据项详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="数据项详情" width="80%" top="5vh">
      <div v-if="selectedItem" class="data-detail">
        <el-tabs v-model="activeDetailTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="数据项ID">{{ selectedItem.itemId }}</el-descriptions-item>
              <el-descriptions-item label="批次ID">{{ selectedItem.batchId }}</el-descriptions-item>
              <el-descriptions-item label="数据类型">{{ getCategoryLabel(selectedItem.category) }}</el-descriptions-item>
              <el-descriptions-item label="处理状态">{{ getStatusLabel(selectedItem.status) }}</el-descriptions-item>
              <el-descriptions-item label="请求URL" :span="2">{{ selectedItem.url }}</el-descriptions-item>
              <el-descriptions-item label="HTTP方法">{{ selectedItem.method }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDate(selectedItem.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDate(selectedItem.updatedAt) }}</el-descriptions-item>
              <el-descriptions-item label="处理时间">{{ formatDate(selectedItem.processedAt) }}</el-descriptions-item>
              <el-descriptions-item label="错误信息" :span="2">
                <el-text v-if="selectedItem.errorMessage" type="danger">{{ selectedItem.errorMessage }}</el-text>
                <el-text v-else>无</el-text>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="请求数据" name="request">
            <pre class="code-block">{{ formatJson(selectedItem.requestData) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="响应数据" name="response">
            <pre class="code-block">{{ formatJson(selectedItem.responseData) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="规则信息" name="rule">
            <pre class="code-block">{{ formatJson(selectedItem.ruleInfo) }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDataManagement } from '../composables/useDataManagement'

const {
  statistics,
  dataItems,
  pagination,
  loading,
  fetchDataItems,
  fetchDataStatistics,
  reprocessDataItem,
  deleteDataItem
} = useDataManagement()

const filterForm = reactive({
  batchId: '',
  category: '',
  status: ''
})

const detailDialogVisible = ref(false)
const selectedItem = ref(null)
const activeDetailTab = ref('basic')

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取数据类型标签
const getCategoryLabel = (category) => {
  const labels = {
    'bank': '银行流水',
    'sales_order': '销售订单',
    'purchase_order': '采购订单',
    'incoming_invoice': '进项发票',
    'outgoing_invoice': '销项发票',
    'invoice': '发票',
    'unknown': '未知'
  }
  return labels[category] || category
}

// 获取状态标签
const getStatusLabel = (status) => {
  const labels = {
    'pending': '待处理',
    'processed': '已处理',
    'failed': '失败'
  }
  return labels[status] || status
}

// 格式化JSON
const formatJson = (data) => {
  if (!data) return '{}'
  try {
    return JSON.stringify(data, null, 2)
  } catch (e) {
    return data.toString()
  }
}

// 获取总批次数（处理数组格式）
const getTotalBatches = () => {
  if (Array.isArray(statistics.value.batchByStatus)) {
    return statistics.value.batchByStatus.reduce((total, item) => {
      return total + (typeof item.count === 'number' ? item.count : 0);
    }, 0);
  }
  return statistics.value.totalBatches || 0;
};

// 获取总记录数（处理数组格式）
const getTotalRecords = () => {
  if (Array.isArray(statistics.value.dataByCategory)) {
    return statistics.value.dataByCategory.reduce((total, item) => {
      return total + (typeof item.count === 'number' ? item.count : 0);
    }, 0);
  }
  return statistics.value.totalRecords || 0;
};

// 刷新数据
const refreshData = async () => {
  await fetchDataStatistics()
  await searchData()
}

// 查询数据
const searchData = async () => {
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    batchId: filterForm.batchId,
    category: filterForm.category,
    status: filterForm.status
  }
  await fetchDataItems(params)
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.batchId = ''
  filterForm.category = ''
  filterForm.status = ''
  searchData()
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchData()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchData()
}

// 查看详情
const viewDetail = (item) => {
  selectedItem.value = item
  detailDialogVisible.value = true
}

// 重新处理数据项
const reprocessItem = async (item) => {
  try {
    item.reprocessing = true
    const result = await reprocessDataItem(item.itemId)
    if (result.success) {
      ElMessage.success(result.message)
      // 更新列表中的状态
      item.status = 'processed'
      item.processedAt = new Date().toISOString()
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error('重新处理失败: ' + error.message)
  } finally {
    item.reprocessing = false
  }
}

// 删除数据项
const deleteItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据项 ${item.itemId} 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteDataItem(item.itemId)
    ElMessage.success('删除成功')
    // 从列表中移除
    const index = dataItems.value.findIndex(i => i.itemId === item.itemId)
    if (index > -1) {
      dataItems.value.splice(index, 1)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 初始化数据
onMounted(async () => {
  await fetchDataStatistics()
  await searchData()
})
</script>

<style scoped>
.data-management-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.code-block {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>